import React, { Component } from 'react';
import { createPortal } from 'react-dom';
import ReactEcharts from 'echarts-for-react';
import darkEchartsTheme from '../../config/theme/darkEchartsTheme';
import echarts from 'echarts';
import { Icon } from 'antd';
import globalStyles from '../../style/common.less';
const modalRoot = document.getElementById('dialog-root');

class BarChartPanel extends Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('barChart_panel');
    this.state = {
      chartOption: undefined,
      chartHeight: 280,
      dtTitle: '',
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.dataList !== this.props.dataList) {
      if (nextProps.dataList) {
        this.setChartData(nextProps.dataList);
        // fix 切换service图层之后 右侧
      }
    }
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
    echarts.registerTheme('theme_name', darkEchartsTheme);
    const { dataList } = this.props;
    if (!dataList) {
      return;
    }
    if (dataList.length > 0) {
      this.setChartData(dataList);
    }
  }

  setChartData(dataList) {
    const { title, rendererItem } = this.props;
    const dtTitle = rendererItem.unit
      ? `${title} （单位：${rendererItem.unit}）TOP5`
      : `${title} TOP5`;
    this.setState({ dtTitle: dtTitle });
    let dataListArray = [];
    for (var i in dataList) {
      dataListArray.push(dataList[i]); //属性
    }
    dataListArray.sort(this.sortBy(rendererItem.id, true));
    const dataLevel = dataListArray[0].regionLevel;
    let dataSource = [];
    var min = dataListArray[0][rendererItem.id];
    var max = dataListArray[0][rendererItem.id];
    if (dataLevel === '630100') {
      var min = dataList[0][rendererItem.id];
      var max = dataList[0][rendererItem.id];
      dataListArray.map((item, index) => {
        const val = item[rendererItem.id];
        val > max ? (max = val) : null;
        val < min ? (min = val) : null;
        dataSource.push([item[rendererItem.id], item[rendererItem.uniqueKey]]);
      });
    } else {
      dataListArray.map((item, index) => {
        if (index < 5) {
          const val = item[rendererItem.id];
          val > max ? (max = val) : null;
          val < min ? (min = val) : null;
          dataSource.push([item[rendererItem.id], item[rendererItem.uniqueKey]]);
        }
      });
    }
    dataSource = dataSource.reverse();
    // 如果为省 显示所有数据 为市时显示前五名  数据取前五  求出最大值 最小值
    const option = {
      // animationDuration: 100,
      dataset: {
        source: dataSource,
      },
      tooltip: {
        show: false,
        trigger: 'item',
        formatter: '{b} : {c}',
      },
      legend: {
        show: false,
      },
      grid: {
        top: '5%',
        left: '3%',
        right: '15%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: { show: false, name: '', splitLine: { show: false } },
      yAxis: {
        axisTick: { show: false },
        axisLine: { show: false },
        splitLine: { show: false },
        type: 'category',
      },
      visualMap: {
        show: false,
        orient: 'horizontal',
        left: 'center',
        min: min,
        max: max,
        text: ['最大值', '最小值'],
        // Map the score column to color
        dimension: 0,
        inRange: {
          // color: ['#83bff6', '#188df0'],
        },
      },
      series: [
        {
          type: 'bar',
          barMaxWidth: 10,
          barGap: '10%',
          barCategoryGap: '10%',
          itemStyle: {
            normal: {
              barBorderRadius: 18,
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                {
                  offset: 1,
                  color: '#00feff',
                },
                {
                  offset: 0.5,
                  color: '#027eff',
                },
                {
                  offset: 0,
                  color: '#0286ff',
                },
              ]),
            },
          },
          label: {
            normal: {
              show: true,
              position: 'right',
              textStyle: {
                color: '#fff',
                fontSize: 12,
              },
            },
          },
          encode: {
            // Map the "amount" column to X axis.
            x: '值',
            // Map the "product" column to Y axis
            y: '地区',
          },
        },
      ],
    };
    this.setState({ chartOption: option });
  }

  sortBy(filed, rev, primer) {
    rev = rev ? -1 : 1;
    return function(a, b) {
      a = a[filed];
      b = b[filed];
      if (typeof primer != 'undefined') {
        a = primer(a);
        b = primer(b);
      }
      if (a < b) {
        return rev * -1;
      }
      if (a > b) {
        return rev * 1;
      }
      return 1;
    };
  }

  render() {
    const { style, width, height } = this.props;
    const { chartOption, dtTitle } = this.state;
    return createPortal(
      <div
        style={{
          ...style,
          display: 'flex',
          flexDirection: 'column',
          width: width,
          height: height,
          color: '#fff',
          backgroundColor: 'rgba(0,0,0,0.6)',
          boxShadow: '0 1px 2px rgba(0,0,0,0.16), 0 1px 2px rgba(0,0,0,0.23)',
        }}
      >
        <div
          style={{
            lineHeight: '35px',
            height: 35,
            borderBottom: '1px solid rgb(238, 238, 238,0.2)',
            textAlign: 'center',
            fontWeight: 'bold'
          }}
        >
          <div style={{ float: 'left', marginLeft: 6, fontSize: 15, fontWeight: 'bold' }}>
            <div
              style={{
                float: 'left',
                width: 5,
                height: 35,
                marginRight: 10,
                backgroundColor: 'rgba(63,177,277,1)',
              }}
            />
            {dtTitle}
          </div>
          <div style={{ float: 'right', marginRight: 8 }}>
            {/* <Icon
              type="close"
              className={`${globalStyles.cursor_style_pointer}`}
              style={{ fontSize: 18 }}
              onClick={this.props.onClose}
            /> */}
          </div>
        </div>
        <div style={{ margin: '3px 8px 3px 8px' }}>
          <div>
            {chartOption !== undefined && (
              <ReactEcharts
                option={chartOption}
                notMerge={true}
                lazyUpdate={true}
                theme={'theme_name'}
                style={{ height: this.state.chartHeight }}
              />
            )}
          </div>
        </div>
      </div>,
      this.el
    );
  }
}

export default BarChartPanel;
